package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AppUser;
import com.ruoyi.common.core.domain.model.LoginAppBody;
import com.ruoyi.framework.web.service.AppLoginService;
import com.ruoyi.user.service.IAppUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@Validated
@Api(value = "APP登录管理", tags = "APP登录管理接口")
@RestController
@RequestMapping("/app")
public class AppLoginController extends BaseController {
    @Resource
    private AppLoginService appLoginService;
    @Resource
    private IAppUserService appUserService;

    @ApiOperation("登录")
    @PostMapping("/login")
    public AjaxResult login(@Valid @RequestBody LoginAppBody loginAppBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = appLoginService.login(loginAppBody.getUsername(), loginAppBody.getPassword());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @ApiOperation("微信小程序登录")
    @GetMapping("/minLogin")
    public AjaxResult minLogin(@ApiParam(value = "code") @Valid @NotBlank(message = "code不能为空") String code) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = appLoginService.minLogin(code);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @ApiOperation("根据token获取用户信息")
    @GetMapping("/userInfo")
    @Anonymous
    public AjaxResult userInfo() {
        AppUser appUser = getLoginAppUser().getAppUser();
        AjaxResult ajax = AjaxResult.success();
        ajax.put("appUser", appUser);
        return ajax;
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/getUserInfo")
    @Anonymous
    public AjaxResult getUserInfo() {
        AppUser appUser = appUserService.selectAppUserByUserId(getLoginAppUser().getAppUser().getUserId());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("appUser", appUser);
        return ajax;
    }


}
